package com.chengxiaoxiao.libarypartner.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.activity.BorrowActivity;
import com.chengxiaoxiao.libarypartner.activity.LoginActivity;
import com.chengxiaoxiao.libarypartner.activity.MultiSelectAdapter;
import com.chengxiaoxiao.libarypartner.constants.AppConsrants;
import com.chengxiaoxiao.libarypartner.domain.ListBooksCategory;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.LoginUtils;
import com.chengxiaoxiao.libarypartner.utils.SPUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BorrowFragment extends Fragment
{
    private CheckBox selectAll;
    private Button selectOpposite;

    //用户存储条目的选择状态
    private Map<Integer, Boolean> isCheck = new HashMap<>();
    //用于存放已选择的条目
    private List<Integer> selectList = new ArrayList<>();

    private TextView submit;
    private MultiSelectAdapter multiSelectAdapter;


    private ListView listBorrow;

    private List<ListBooksCategory> list;


    private String[] borrowNames = new String[]{"图书榜", "新书榜", "新书上架", "热门作者", "猜你喜欢"};
    private int[] borrowIcon = {R.drawable.fragment_index_book1, R.drawable.fragment_index_book2, R.drawable.fragment_index_book3, R.drawable.fragment_index_book4, R.drawable.fragment_index_book5};

    private LinearLayout lineEmpty;
    private Button btnLogin;
    private TextView textEmpty;
    private TextView textSelected;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        View view = inflater.inflate(R.layout.fragment_borrow, container, false);
        lineEmpty = (LinearLayout) view.findViewById(R.id.lineEmpty);
        listBorrow = (ListView) view.findViewById(R.id.listBorrow);
        btnLogin = (Button) view.findViewById(R.id.btnLogin);
        textEmpty = (TextView) view.findViewById(R.id.textEmpty);
        textSelected = (TextView)view.findViewById(R.id.textSelected);

        initView(view);


        return view;
    }

    /**
     * 初始化布局和数据
     * @param view
     */
    private void initView(View view)
    {
        selectAll = (CheckBox) view.findViewById(R.id.multi_btn_all);
        //selectOpposite = (Button) view.findViewById(R.id.multi_btn_opposite);
        submit = (TextView) view.findViewById(R.id.multi_btn_submit);

        list = new ArrayList<ListBooksCategory>();

        //清空集合中的数据
        list.clear();
        initBorrow();
        initListener();
    }


    private void initData()
    {
        multiSelectAdapter = new MultiSelectAdapter(list, isCheck, getActivity());
        listBorrow.setAdapter(multiSelectAdapter);
        //        //设置数据
        //        if (multiSelectAdapter == null) {
        //
        //        } else {
        //            multiSelectAdapter.notifyDataSetChanged();
        //        }


    }

    private void initListener()
    {
        //全选
        selectAll.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (selectAll.isChecked())
                {
                    for (int i = 0; i < list.size(); i++)
                    {
                        //把集合中所有的选项设置为true,刷新布局
                        isCheck.put(i, true);
                    }
                }
                else
                {
                    for (int i = 0; i < list.size(); i++)
                    {
                        //把集合中所有的选项设置为true,刷新布局
                        isCheck.put(i, false);
                    }
                }


                initData();
            }
        });

        textSelected.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (selectAll.isChecked())
                {
                    for (int i = 0; i < list.size(); i++)
                    {
                        //把集合中所有的选项设置为true,刷新布局
                        isCheck.put(i, false);
                    }
                    selectAll.setChecked(false);
                }
                else
                {
                    for (int i = 0; i < list.size(); i++)
                    {
                        //把集合中所有的选项设置为true,刷新布局
                        isCheck.put(i, true);
                    }
                    selectAll.setChecked(true);
                }

                initData();
            }
        });




        //提交
        submit.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //清除之前选择的数据
                selectList.clear();
                //遍历map集合
                for (int key : isCheck.keySet())
                {
                    //判断是否已选择，如果已选择，则添加进selectList
                    if (isCheck.get(key))
                    {
                        selectList.add(key);
                    }
                }

                //Toast.makeText(getActivity(), selectList.toString(), Toast.LENGTH_SHORT).show();
                String ids = "";

                for (int i = 0;i<selectList.size() ; i++) {
                    ids+=","+list.get(selectList.get(i)).getId();
                }

                SPUtils.putString(AppConsrants.BORROW_LIST_ID,ids,getActivity());

                Intent intent1 = new Intent(getActivity(), BorrowActivity.class);
                intent1.putExtra(AppConsrants.SCAN_BORROW_IDS, ids);
                startActivity(intent1);

                ToastUtils.makeText(getActivity(),ids);

            }
        });
    }

    private void initBorrow()
    {
        //list = new ArrayList<>();
        String ids = SPUtils.getString(AppConsrants.BORROW_LIST_ID, "", getActivity());
        if (ids.trim().equalsIgnoreCase(""))
        {
            boolean isLogin = LoginUtils.getLoginStatus(getActivity());

            if (!isLogin)
            {
                lineEmpty.setVisibility(View.VISIBLE);

                btnLogin.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }
                });

            } else
            {
                btnLogin.setVisibility(View.GONE);
                textEmpty.setText("借书单空空哒~");
                lineEmpty.setVisibility(View.VISIBLE);
            }
            return;

        }

        String[] id = ids.split(",");
        count=0;

        for (int i = 0; i < id.length; i++)
        {
            if (id[i].trim().equalsIgnoreCase(""))
            {
                continue;
            }
            //ToastUtils.makeText(getActivity(),id[i]);
            loadBooks(id[i]);

        }


    }

    int count = 0;

    /**
     * 根据ID加载书籍信息
     * @param id
     */
    private void loadBooks(String id)
    {
        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=getBooksByid&id=" + id, new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {

                String body = new String(responseBody);
                try
                {
                    JSONObject jsonObj = new JSONObject(body);

                    int id = jsonObj.getInt("id");
                    String author = jsonObj.getString("author");
                    String bookName = jsonObj.getString("name");
                    int number = jsonObj.getInt("number");
                    String categporyName = jsonObj.getString("categoryName");
                    String imagesPath = jsonObj.getString("imagesSrc");
                    String address = jsonObj.getString("address");

                    //TODO:增加对图片和所在位置的判断
                    ListBooksCategory book = new ListBooksCategory(id, bookName, author, categporyName, imagesPath, number, address);

                    list.add(book);

                    isCheck.put(count++, true);

                    initData();


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //listBorrow.setAdapter(new BorrowAdapter());


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(getActivity(), "网络连接错误");
            }
        });
    }

    class BorrowAdapter extends BaseAdapter
    {

        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public Object getItem(int position)
        {
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view;
            if (convertView == null)
            {
                view = View.inflate(getActivity(), R.layout.list_item_borrow, null);
            } else
            {
                view = convertView;
            }

            SmartImageView imageIcon = (SmartImageView) view.findViewById(R.id.ivIcon);
            TextView textName = (TextView) view.findViewById(R.id.textName);
            TextView textAddress = (TextView) view.findViewById(R.id.textAddress);
            ListBooksCategory book = list.get(position);

            textName.setText(book.getBookName());
            textAddress.setText(book.getAddress());

            imageIcon.setImageUrl(book.getImagePath());

            return view;
        }
    }


    /**
     * 每次进入重新加载
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden)
    {
        super.onHiddenChanged(hidden);
        //清空集合中的数据
        isCheck.clear();
        selectList.clear();
        list.clear();
        initBorrow();
    }


}
